
import { controller } from '../utils/service';
import { ctx } from '../utils/iface';
const proxy: any = require('koa-better-http-proxy')
import { session } from '../middlewares/session'
export default async function router(ctx: ctx | any, next: Function | any) {
    let proxyConfig: string | { Host: string, Options: Object } | boolean = ctx.config.checkProxy;
    if (proxyConfig !== false) {
        ctx.config.sendFile = true;
        //用于支持自定义的代理，文档地址：https://github.com/vagusX/koa-proxies
        if ('string' == typeof proxyConfig) {
            await proxy(proxyConfig)(ctx, next);
        } else if ('object' == typeof proxyConfig && proxyConfig.Host) {
            if (proxyConfig.Options && Object.keys(proxyConfig.Options).length > 0) {
                await (proxy(proxyConfig.Host, proxyConfig.Options))(ctx, next);
            } else {
                await proxy(proxyConfig)(ctx, next);
            }
        }
    } else if (ctx.control && ctx.control.m && ctx.control.c) {
        try {
            ctx.req.body = Object.assign(ctx.req.body ? ctx.req.body : {}, ctx.request.body ? ctx.request.body : {})
            let res = await controller(ctx.control.c, ctx.control.m, ctx);
            if (ctx.config.sendFile === false) { ctx.body = res }
        } catch (e) {
            ctx.error = { m: "string" == typeof e ? e : e.message, }
            if (ctx.config.AppDebug) {
                ctx.error.e = e.stack
            }
        } finally {
            next();
        }
    } else if (ctx.method == "GET") {
        try {
            await ctx.config.getStaticFile()
        } catch (error) {
            console.error(error)
        }
        next();
    } else {
        next();
    }
}